package com.zf.skywalking.controller;

import com.zf.common.core.result.RestResponse;
import com.zf.skywalking.service.HelloService;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Zhou Feng
 */
@RestController
@RequestMapping(value = "/hello")
public class HelloController {
    private static final Logger LOGGER = LoggerFactory.getLogger(HelloController.class);

    @Autowired
    private HelloService helloService;


    /**
     * 普通接口，默认情况下，skywalking 会记录controller请求路径，但不会记录出入参数，同时也不会深入到service层
     */
    @GetMapping(value = "/test")
    public RestResponse<?> test(@RequestParam(name = "id", required = false) String id) {
        // int a = 1/0; skywalking会自动抓取到异常信息
        return RestResponse.success(id);
    }


    /**
     * 自定义skywalking追踪节点，controller层
     */
    @GetMapping(value = "/test-custom-ctrl-node")
    // Trace注解标识我们自定义的链路追踪节点
    @Trace
    // Tags注解可以给我们的追踪节点添加更详细的信息，如入参和返回
    @Tags({
            //  在自定义的追踪链路中记录返回值，key是记录的名称，自定义即可；
            //  returnedObj值是固定的，表示返回对象，可以用 returnedObj.code 获取返回中的code属性
            @Tag(key = "result", value = "returnedObj"),
            @Tag(key = "resultCode", value = "returnedObj.code"),
            //  在自定义的追踪链路中记录入参，arg[X]对应入参下标
            @Tag(key = "id", value = "arg[0]")
    })
    public RestResponse<?> testCustomControllerNode(@RequestParam(name = "id", required = false) String id) {
        return RestResponse.success(id);
    }

    /**
     * 自定义skywalking追踪节点，service层
     */
    @GetMapping(value = "/test-custom-serv-node")
    public RestResponse<?> testCustomServiceNode(@RequestParam(name = "name", required = false) String name,
                                                 @RequestParam(name = "gender", required = false) String gender) {
        return RestResponse.success(helloService.testCustomServiceNode(name, gender));
    }


    /**
     * 测试skywalking本地日志打印和上报
     */
    @GetMapping(value = "/test-local-log")
    public RestResponse<?> testLocalLog() {
        LOGGER.info("testLocalLog 方法");
        return RestResponse.success();
    }
}
